import type { Directive, DirectiveBinding } from "vue";
import { logPv, getAllThing } from "@/api/thing/index";
import type { LogPvReq } from "@/api/type/thing";

interface ElType extends HTMLElement {
	options: Record<string, any>;
	callback: (entries: []) => any;
	observer: IntersectionObserver;
	debounce: (fn) => any;
}

const buried: Directive = {
	mounted(el: ElType, binding: DirectiveBinding) {
		//记录已经上报过的埋点信息
		let visuallyList = [];
		console.log(visuallyList);
		if (visuallyList.includes(binding.value)) {
			return;
		}
		el.options = {
			root: null, //默认浏览器视窗
			threshold: 1, //元素完全出现在浏览器视窗内才执行callback函数。
		};
		//增加定时器对象
		let timer = {};

		el.callback = (entries: []) => {
			entries.forEach((entry: Record<string, any>) => {
				let visuallyData: LogPvReq ;
				try {
					visuallyData = JSON.parse(entry.target.getAttribute("visually-data"));
					console.log("visuallyData", visuallyData);
				} catch (error) {
					visuallyData = null;
					console.error("埋点数据格式异常", error);
				}
				//没有埋点数据取消上报
				if (!visuallyData) {
					el.observer.unobserve(entry.target);
					return;
				}

				if (entry.isIntersecting) {
					
					timer[visuallyData.id] = setTimeout(async () => {
						const res = await logPv(visuallyData);
						if (res.data.code === 200) {
							//上报成功后取消监听
							el.observer.unobserve(entry.target);
							visuallyList.push(visuallyData.id);
							console.log(visuallyList);
							timer[visuallyData.id] = null;
						}
					}, 5000);
				} else {
					if (timer[visuallyData.id]) {
						clearTimeout(timer[visuallyData.id]);
						timer[visuallyData.id] = null;
					}
				}
			});
		};

		// 防抖处理页面滚动
		el.debounce = function (fn) {
			let timer: NodeJS.Timeout | null = null;
			return function () {
				let self = this;
				let args = arguments;
				if (timer) {
					clearTimeout(timer);
				}
				timer = setTimeout(() => {
					fn.apply(self, args);
				}, 1000);
			};
		};
		el.observer = new IntersectionObserver(
			el.debounce(el.callback),
			el.options
		);

		el.observer.observe(el);
	},
	unmounted(el: ElType) {
		el.observer.unobserve(el);
	},
};

export default buried;
